<template>
    <el-container>
        <el-header>
            <el-form inline>
                <el-form-item label="用户名字">
                    <el-input v-model.trim="search.user_name" @change="updateList()"></el-input>
                </el-form-item>
                <el-form-item label="用户角色">
                    <el-select v-model="search.role_id" @change="updateList()">
                        <el-option label="- 请选择" :value="-1"></el-option>
                        <el-option label="- 无角色" :value="0"></el-option>
                        <el-option v-for="item in roleStore.allRoles" :key="item.role_id" :label="item.role_name"
                            :value="item.role_id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </el-header>
        <el-main>
            <el-table :data="list" style="width: 100%" border>
                <el-table-column type="index" label="#" width="60" align="center"></el-table-column>
                <el-table-column prop="user_name" label="用户名" width="100">

                </el-table-column>
                <el-table-column label="角色名字" width="150">
                    <template #default="{ row }">
                        <span v-if="row.role_id === null">-无角色-</span>
                        <span v-else>{{
        roleStore.allRoles.find((item) => item.role_id === row.role_id)
            ?.role_name
}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #header>
                        <el-button type="primary" size="default" @click="beginAdd">新增</el-button>

                    </template>
                    <template #default="{ row }">
                        <el-button @click="resetPwd(row)">重置密码</el-button>
                        <el-button @click="beginRoleConfig(row)">分配角色</el-button>
                        <el-button @click="remove(row)">删除用户</el-button>
                    </template>
                </el-table-column>

            </el-table>
        </el-main>
        <el-footer>
            <el-pagination background layout="prev, pager, next,jumper->, total,sizes" :total="pagination.total"
                v-model:page-size="pagination.pageSize" :page-sizes="[6, 8, 10, 12]"
                v-model:current-page="pagination.currentPage" @size-change="updateList()"
                @current-change="updateList" />
        </el-footer>
    </el-container>
    <el-dialog v-model="userEdit.isEdit" title="新增用户">
        <el-form :model="userEdit.model" :rules="userEdit.rules" :ref="(el: any) => userEdit.formRef = el">
            <el-form-item label="用户名:" prop="user_name">
                <el-input v-model="userEdit.model.user_name"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="save">保存</el-button>
                <el-button @click="userEdit.isEdit = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <el-dialog v-model="roleConfig.isEdit" title="用户角色分配">
        <el-form>
            <el-form-item label="用户名:">
                <span>{{ roleConfig.model.user_name }}</span>

            </el-form-item>
            <el-form-item label="用户角色:">
                <el-select v-model="roleConfig.model.role_id" @change="updateList()">

                    <el-option label="- 无角色" :value="0"></el-option>
                    <el-option v-for="item in roleStore.allRoles" :key="item.role_id" :label="item.role_name"
                        :value="item.role_id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="default" @click="saveRoleConfig">确定</el-button>
                <el-button type="primary" size="default" @click="roleConfig.isEdit = false">取消</el-button>

            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup lang="ts">
import { reactive, onMounted, markRaw, nextTick } from 'vue';
import type { Raw } from 'vue';
import { FormRules, FormInstance, ElTree } from "element-plus";
import { useRoleStore } from '@/store';
import { UserApi } from '@/api';
import { ElMessageBox, ElMessage } from "element-plus";

const roleStore = useRoleStore();
const userEdit = reactive<{ isEdit: boolean; formRef: null | FormInstance; model: HttpPayload.UserEdit; rules: Raw<FormRules> }>({
    isEdit: false,
    model: { user_name: "", user_pwd: "123" },
    formRef: null,
    rules: markRaw({
        user_name: [
            { required: true, message: "* 用户名不能为空", trigger: "blur" },
            { min: 2, max: 2, message: "* 用户名长度 2 - 2", trigger: "blur" }

        ],
    }),
});
const roleConfig = reactive<{ isEdit: boolean; model: HttpPayload.UserRole; }>({
    isEdit: false,
    model: { user_name: "", role_id: 0 },

});
const list = reactive<Array<Vm.User>>([]);
const search = reactive({
    user_name: "",
    role_id: -1,
});
const pagination = reactive({
    currentPage: 1,
    pageSize: 6,
    total: 0,
})
const updateList = (async (currentPage: number = 1) => {
    pagination.currentPage = currentPage;
    list.splice(0, list.length)
    const result = await UserApi.getList({ ...search, begin: (pagination.currentPage - 1) * pagination.pageSize, pageSize: pagination.pageSize })
    list.push(...result.list);
    pagination.total = result.total;

})

onMounted(async () => {
    try {
        await roleStore.init();
        updateList()
    } catch (e) {/** */ }

})
const resetPwd = async (user: Vm.User) => {
    try {
        //问用户是不是确定删除
        await ElMessageBox.confirm(`确定重置:"${user.user_name}"的密码吗?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        });
        // 发ajax从数据库中删除功能
        await UserApi.resetPwd({ user_name: user.user_name, user_pwd: "123" })
        //从allFuncs中删除功能,更新页面
        ElMessage({ type: "success", message: `重置用户:"${user.user_name}"的密码成功` });
    } catch (e) {
        /**/
    }
}
const remove = async (user: Vm.User) => {
    try {
        //问用户是不是确定删除
        await ElMessageBox.confirm(`确定删除:"${user.user_name}"的密码吗?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        });
        // 发ajax从数据库中删除功能
        await UserApi.remove(user.user_name);
        updateList();
        //从allFuncs中删除功能,更新页面
        ElMessage({ type: "success", message: `用户："${user.user_name}"删除成功` });
    } catch (e) {
        /**/
    }
};
const beginAdd = (() => {
    userEdit.formRef?.resetFields();
    userEdit.model.user_name = "";
    nextTick(() => userEdit.isEdit = true);
})

const save = async () => {
    try {
        await userEdit.formRef?.validate();
        const flag = await UserApi.validName({ user_name: userEdit.model.user_name })
        if (flag === 1) {
            ElMessage({ type: "success", message: `用户："${userEdit.model.user_name}"已存在` });
            return;
        }
        await UserApi.add(userEdit.model)
        await updateList();
        ElMessage({ type: "success", message: `用户："${userEdit.model.user_name}"新增成功` });
        userEdit.isEdit = false;
    } catch (e) {
        { /** */ };
    }
}
const beginRoleConfig = (user: Vm.User) => {
    roleConfig.model.user_name = user.user_name;
    // roleConfig.model.role_id=user.role_id === null ? 0 :user.role_id
    roleConfig.model.role_id = user.role_id || 0
    nextTick(() => roleConfig.isEdit = true);
};
const saveRoleConfig = async () => {
    try {
        await UserApi.roleConfig(roleConfig.model);
        (list.find(item => item.user_name === roleConfig.model.user_name) as Vm.User).role_id = roleConfig.model.role_id === 0 ? null : roleConfig.model.role_id
        ElMessage({ type: "success", message: `用户："${roleConfig.model.user_name}"分配成功` });
        roleConfig.isEdit = false;
    } catch (e) {
        { /** */ };
    }
};
</script>

<style lang="stylus" scoped>
    
</style>